import datetime
import os
import json
import uuid

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
import redis
from dashscope import Generation

# Create your views here.

redis_client = redis.Redis(
    host='localhost',
    port=6379,
    db=0,
)

REDIS_TTL_SECONDS = 86400 * 7
REDIS_USER_PREFIX = "qa:user:"
REDIS_SESSION_PREFIX = "qa:session:"


def _redis_user_key(user_id: str) -> str:
    return f"{REDIS_USER_PREFIX}{user_id}"


def _redis_session_key(user_id: str) -> str:
    return f"{REDIS_SESSION_PREFIX}{user_id}"


def _load_messages(user_id: str) -> list:
    raw = redis_client.get(_redis_user_key(user_id))
    return json.loads(raw) if raw else []


def _save_messages(user_id: str, messages: list) -> None:
    redis_client.setex(_redis_user_key(user_id), REDIS_TTL_SECONDS, json.dumps(messages, ensure_ascii=False))


def _save_session_info(user_id: str) -> None:
    session_info = {
        "user_id": user_id,
        "create_time": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    }
    redis_client.setex(_redis_session_key(user_id), REDIS_TTL_SECONDS, json.dumps(session_info, ensure_ascii=False))


def _get_api_key() -> str:
    key = os.getenv('DASHSCOPE_API_KEY')
    if not key:
        raise RuntimeError('DASHSCOPE_API_KEY not set')
    return key

#多轮对话视图

class MUltiRoundChatView(APIView):
    def post(self, request):
        message = request.data.get('message')
        if not message:
            return Response({'error': '消息不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        # 优先从请求体获取 user_id；否则：登录用户 id 或新建 uuid
        user_id = request.data.get('user_id')
        if not user_id:
            user_id = str(getattr(request.user, 'id', '') or uuid.uuid4())
            messages = []
        else:
            messages = _load_messages(user_id)

        messages.append({'role': 'user', 'content': message})
        try:
            response = Generation.call(
                api_key=_get_api_key(),
                model='qwen-plus',
                messages=messages,
                result_format='message'
            )
            assistant_message = response.output.choices[0].message.content
            messages.append({'role': 'assistant', 'content': assistant_message})
            _save_messages(user_id, messages)
            # 如果是新会话，也保存会话信息
            if not redis_client.get(_redis_session_key(user_id)):
                _save_session_info(user_id)
            return Response({
                'user_id': user_id,
                'message': message,
                'answer': assistant_message
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



#创建新对话视图
class CreateNewConversationView(APIView):
    def post(self, request):
        # 总是创建新的会话 ID
        user_id = str(uuid.uuid4())

        # 可选：初始问候由模型生成
        init_user_prompt = '你好，我是小Q，很高兴为您服务。'
        messages = [{'role': 'user', 'content': init_user_prompt}]
        try:
            response = Generation.call(
                api_key=_get_api_key(),
                model='qwen-plus',
                messages=messages,
                result_format='message'
            )
            assistant_message = response.output.choices[0].message.content
            messages.append({'role': 'assistant', 'content': assistant_message})

            _save_messages(user_id, messages)
            _save_session_info(user_id)

            return Response({
                'user_id': user_id,
                'message': init_user_prompt,
                'answer': assistant_message
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


















#获取对话历史
class GetHistoryConversationView(APIView):
    def get(self, request, user_id):
        history = redis_client.get(_redis_user_key(user_id))
        session_info = redis_client.get(_redis_session_key(user_id))

        messages = json.loads(history) if history else []
        session = json.loads(session_info) if session_info else None
        return Response({'history': messages, 'session_info': session}, status=status.HTTP_200_OK)








#获取对话列表
class GetConversationList(APIView):
    def get(self, request):
        sessions = redis_client.keys(f"{REDIS_SESSION_PREFIX}*")
        session_list = []
        for key in sessions:
            info = redis_client.get(key)
            if info:
                try:
                    session_list.append(json.loads(info))
                except Exception:
                    continue
        return Response({'session_list': session_list}, status=status.HTTP_200_OK)




















